// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import HeroControl, {effectAnimName} from "./HeroControl";
import GameData_red_blue_man, {dataName, emitType} from "./GameData_red_blue_man";
import cardinalSplineBy = cc.cardinalSplineBy;
import GameControl_red_blue_man from "./GameControl_red_blue_man";
import ControlScript from "../PublicScript/ControlScript";
import Camera_control from "./Camera_control";
import Music, {musicName} from "../PublicScript/Music";
import SkinShop from "./SkinShop";

import NewPlay from "./NewPlay";
import data = cc.data;

const {ccclass, property} = cc._decorator;

export enum man {
    blue ,
    red,
}

@ccclass
export default class GameUi extends cc.Component {

    @property({tooltip: "按钮", type: cc.Node})
    btnNodeParent: cc.Node = null;
    @property({type: cc.Node,displayName:"按键"})
    btnNode: cc.Node[] = [];
    @property({tooltip: "钥匙", type: cc.Node})
    keyNode: cc.Node[] = [];
    @property({type: cc.Label})
    levelLabel: cc.Label = null;
    @property(cc.Node)
    levelNode: cc.Node = null;
    @property({tooltip: "退出演示", type: cc.Node})
    returnGuide: cc.Node = null;
    @property({tooltip: "提示", type: cc.Node})
    tips: cc.Node = null;
    @property({tooltip: "新手指导", type: cc.Node})
    newPlay: cc.Node = null;


    newPlayScript = null;

    btnNodeList = [];

    //现在选中的人物节点
    pitch_on_hero = null;
    //现在选中人物的脚本
    pitch_on_script = null;
    //红色角色
    red_man = null;
    //蓝色角色
    blue_man = null;
    //获取主相机
    mainCameraScript = null;

    initTime = 0;

    newPlayIndex = 1;

    onLoad () {
        this.btnNodeList = this.btnNodeParent.children;

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);

        this.init();

        cc.game.on(emitType.getKey, this.getKey, this);
        cc.game.on(emitType.newSkinExper, this.initAnim, this);
        cc.game.on("newPlay", ()=>{
            console.log("this.newPlayIndex:", this.newPlayIndex);
            if(this.newPlayIndex == 5 && GameData_red_blue_man.settingState.newPlay && GameData_red_blue_man.highestLevel == 1){
                this.newPlayIndex += 1;
                this.btnNode[4].active = true;
                this.scheduleOnce(()=>{
                    this.newGuide(4);
                },0.1)
            }
        }, this);
        // cc.game.on("consoleGuide", ()=>{console.log(JSON.stringify(this.guidanceData))}, this);

        this.initTime = new Date().getTime();
    }

    start () {
        this.changeUi(man.red);
        this.addClickEvent();
    }

    onClick(touch,data){
        //todo 增加音效
        Music.GamePlayEffect(musicName.click);
        let num = parseInt(data);

        if(num == 6){       //退出指导
            GameData_red_blue_man.isGuiding = false;
            // QQSDKManner.GetInstance().destroyBanner();
            cc.director.loadScene("GameScene");
        }
        if(GameControl_red_blue_man.gameState){
            return;
        }
        if(num == 1){           //切换人物
            if(GameData_red_blue_man.isGuiding){
                return;
            }

            this.cut_man(); 
        }
        if(num == 2){           //视角

        }
        if(num == 3){           //设置
            ControlScript.instantiate("setting")
        }
        if(num == 4){          //跳过
            GameData_red_blue_man.showVideo({callback: ()=>{
                    GameData_red_blue_man.nextGame(1);
                }, name: "游戏界面跳关"})
        }
        if(num == 5){       //进入指导
            GameData_red_blue_man.showVideo({callback: ()=>{
                    GameData_red_blue_man.isGuiding = true;
                    cc.director.loadScene("GameScene");
                }});
        }
    }

    //起始时间
    // initTime = 0;
    //保存数据
    guidanceData = null;
    //对应的关卡
    levelName = null;
    //"100_50,50|200_100,100"

    getTime(name){
        // let time = new Date().getTime() - this.initTime;
        // this.guidanceData[this.levelName][name].push(time);
    }

    init(){
        this.levelNode.active = false;
        for(let i of this.btnNodeList){
            i.children[0].active = false;
            i.children[1].active = false;
        }
        this.mainCameraScript = cc.Camera.findCamera(cc.find("Canvas")).getComponent(Camera_control);
        this.levelLabel.string = GameData_red_blue_man.highestLevel + "";
        if(SkinShop.experienceSkinIndex){
            this.initAnim();
        }
        // this.initTime = new Date().getTime();
        this.levelName = "level"+ GameData_red_blue_man.highestLevel;

        this.returnGuide.active = GameData_red_blue_man.isGuiding;
        if(GameData_red_blue_man.highestLevel < 71){
            this.tips.active = !GameData_red_blue_man.isGuiding;
        }else{
            this.tips.active = false;
        }

        // this.guidanceData = {};
        // this.guidanceData[this.levelName] = {};
        // this.guidanceData[this.levelName]["leftMove"] = [];
        // this.guidanceData[this.levelName]["rightMove"] = [];
        // this.guidanceData[this.levelName]["stopMove"] = [];
        // this.guidanceData[this.levelName]["jump"] = [];
        // this.guidanceData[this.levelName]["cutMan"] = [];

        if(GameData_red_blue_man.isGuiding){
            for(let i of this.btnNode){
                i.active = false;
            }
            this.guidanceData = {};
            this.guidanceData = GameData_red_blue_man.getGuide()[GameData_red_blue_man.highestLevel - 1];

            this.guide("leftMove", this.leftMoveSetInterval, ()=>{this.leftMove()});
            this.guide("rightMove", this.rightMoveSetInterval, ()=>{this.rightMove()});
            this.guide("stopMove", this.stopMoveSetInterval, ()=>{this.stopMove()});
            this.guide("jump", this.jumpSetInterval, ()=>{this.jump()});
            this.guide("cutMan", this.cut_manSetInterval, ()=>{this.cut_man()});
        }

        this.newPlay.active = false;
        this.newPlayScript = this.newPlay.getComponent(NewPlay);
        if(GameData_red_blue_man.highestLevel == 1){
            this.scheduleOnce(()=>{
                this.newPlay.active = GameData_red_blue_man.settingState.newPlay;
                this.newGuide(1);
            },0.1);
            this.btnNode[4].active = !GameData_red_blue_man.settingState.newPlay;
        }
    };

    //计时器
    leftMoveSetInterval = null;
    rightMoveSetInterval = null;
    stopMoveSetInterval = null;
    jumpSetInterval = null;
    cut_manSetInterval = null;

    //执行新手引导
    newGuide(btn_index, size?){
        if(GameData_red_blue_man.highestLevel != 1){
            return;
        }
        let new_size = size ? 0 : this.btnNode[btn_index].width + 10;
        if(GameData_red_blue_man.settingState.newPlay){
            this.newPlayScript.init({position:this.btnNode[btn_index].position, index: this.newPlayIndex - 1, size: new_size});
        }
    }

    //执行操作
    guide(name, interval, call){
       
        if(this.guidanceData[this.levelName][name].length < 1){
            return;
        }
        let index = 0;
        let time = this.guidanceData[this.levelName][name][index];
        let func2 = (timeCount, interval, call)=>{
            interval = setInterval(()=>{
                console.log("执行", name, interval);
                clearInterval(interval);
                if(!GameData_red_blue_man.isGuiding){
                    return;
                }
                index ++;
                call();
                if(this.guidanceData[this.levelName][name].length > 1 && index < this.guidanceData[this.levelName][name].length){
                    console.log(index);
                    let newTime = ((this.guidanceData[this.levelName][name][index]) - (this.guidanceData[this.levelName][name][index - 1]));
                    console.log(newTime);
                    func2(newTime, interval, call);
                }
            }, timeCount);
            switch (name) {
                case "leftMove":
                    this.leftMoveSetInterval = interval;
                    console.log("第二次打印",this.leftMoveSetInterval);
                    break;
                case "rightMove":
                    this.rightMoveSetInterval = interval;
                    console.log("第二次打印",this.rightMoveSetInterval);
                    break;
                case "stopMove":
                    this.stopMoveSetInterval = interval;
                    console.log("第二次打印",this.stopMoveSetInterval);
                    break;
                case "jump":
                    this.jumpSetInterval = interval;
                    console.log("第二次打印",this.jumpSetInterval);
                    break;
                case "cutMan":
                    this.cut_manSetInterval = interval;
                    console.log("第二次打印",this.cut_manSetInterval);
                    break;
            }
        };

        func2(time, interval, call);
    }

    clearAllInterval(){
        // console.log(this.leftMoveSetInterval, this.rightMoveSetInterval, this.stopMoveSetInterval, this.jumpSetInterval, this.cut_manSetInterval);
        clearInterval(this.leftMoveSetInterval);
        clearInterval(this.rightMoveSetInterval);
        clearInterval(this.stopMoveSetInterval);
        clearInterval(this.jumpSetInterval);
        clearInterval(this.cut_manSetInterval);
    }

    //做一个外部存储
    externalStorage(data){
        if(!CC_JSB){
            return;
        }
        // jsb.fileUtils获取全局的工具类的实例, cc.director;
        // 如果是在电脑的模拟器上，就会是安装路径下模拟器的位置;
        // 如果是手机上，那么就是手机OS为这个APP分配的可以读写的路径;
        // jsb --> javascript binding --> jsb是不支持h5的
        let writeable_path = jsb.fileUtils.getWritablePath();
        console.log(writeable_path);
        // 要在可写的路径先创建一个文件夹
        let new_dir = writeable_path + "new_dir";
        // 路径也可以是 外部存储的路径，只要你有可写外部存储的权限;
        // getWritablePath这个路径下，会随着我们的程序卸载而删除,外部存储除非你自己删除，否者的话，卸载APP数据还在;
        if(!jsb.fileUtils.isDirectoryExist(new_dir)) {      //jsb.fileUtils.isDirectoryExist(path): 判断路径是否存在;
            jsb.fileUtils.createDirectory(new_dir);         //jsb.fileUtils.createDirectory(path); 创建一个路径;
        }else {
            console.log("路径已经存在!!!");
        }
        // 读写文件我们分两种,文本文件, 二进制文件;
        // (1)文本文件的读,返回的是一个string对象
        let str_data = jsb.fileUtils.getStringFromFile(new_dir + "/red_blue_man.txt");     //jsb.fileUtils.getStringFromFile(path); 获取文本数据; // data String
        console.log(str_data);
        str_data = JSON.stringify(data);
        jsb.fileUtils.writeStringToFile(str_data, new_dir + "/red_blue_man.txt");         //jsb.fileUtils.writeStringToFile(data,path); 写文本文件; // data String对象

        // (2)二进制文件的读写, Uint8Array --> js对象
        // let bin_array = jsb.fileUtils.getDataFromFile(new_dir + "/test_bin_read.png");          //jsb.fileUtils.getDataFromFile(path)获取二进制数据; // Uint8Array文本
        // console.log(bin_array[0], bin_array[1]); // 使用这个就能访问二进制的每一个字节数据;
        // jsb.fileUtils.writeDataToFile(bin_array, new_dir + "/test_bin_write.png");              //jsb.fileUtils.writeDataToFile(data,path); 写二进制数据; // Uint8Array 对象

        // 删除文件和文件夹
        // jsb.fileUtils.removeFile(new_dir + "/red_blue_man.png");         //jsb.fileUtils.removeFile(path); 删除掉一个文件;
        // jsb.fileUtils.removeDirectory(new_dir);
    }

    changeUi(num){
        let other = num == 1 ? 0 : 1;
        for(let i of this.btnNodeList){
            i.children[num].active = true;
            i.children[other].active = false;
        }
    }

    set_man(node){
        this.pitch_on_hero = node;
        this.pitch_on_script = node.getComponent(HeroControl);
    }

    get_man(data){
        this.red_man = data.red_man;
        this.blue_man = data.blue_man;
    }

    //切换主角
    cut_man(){
        if(GameControl_red_blue_man.gameState){
            return
        }
        // this.getTime("cutMan");
        Music.GamePlayEffect(musicName.PlayerSwap);
        let num = 0;
        this.pitch_on_script.stopMove(true);
        this.pitch_on_hero.getChildByName("headTip").active = false;
        this.stopMove();

        if(this.pitch_on_hero == this.red_man){
            this.set_man(this.blue_man);
            num = 0;
        }else if(this.pitch_on_hero == this.blue_man){
            this.set_man(this.red_man);
            num = 1;
        }
        this.pitch_on_hero.getChildByName("headTip").active = true;
        cc.game.emit(emitType.cutMan, this.pitch_on_hero);
        this.changeUi(num);
        this.pitch_on_script.effect_anim({animName: effectAnimName.smoke2, loop: false});

        if(this.newPlayIndex == 6 && GameData_red_blue_man.settingState.newPlay  && GameData_red_blue_man.highestLevel == 1){
            this.newPlayIndex += 1;
            this.scheduleOnce(()=>{
                this.newGuide(4);
            }, 1);
        }
    }

    //相机
    cameraEvent(state){
        if(GameControl_red_blue_man.gameState){
            return
        }
        this.mainCameraScript.scaleCamera(state);
    }

    //人物移动
    manMove(){
        this.pitch_on_script.move(this.dir);
    }

    stopMove(){
        Music.stopSpecialMusic({name: musicName.tuigreen});
        this.unschedule(this.manMove);
        this.pitch_on_script.stopMove()
    }

    dir = 0;
    clickMove(dir){
        this.dir = dir;
        this.schedule(this.manMove,0.02);
        this.manMove();
    }

    //向左走
    leftMove(){
        this.clickMove(-1);
    }
    //向右走
    rightMove(){
        this.clickMove(1);
    }
    //跳跃
    jump(){
        this.pitch_on_script.jump()
    }

    addClickEvent(){
        if(GameData_red_blue_man.isGuiding){
            return;
        }
        this.btnNode[0].on("touchstart", ()=>{
            // this.getTime("leftMove");
            if(this.newPlayIndex == 2 && GameData_red_blue_man.settingState.newPlay  && GameData_red_blue_man.highestLevel == 1){
                this.newPlayIndex += 1;
                this.scheduleOnce(()=>{
                    this.newGuide(2);
                }, 1);
            }
            this.clickMove(-1);
        }, this);
        this.btnNode[0].on("touchcancel", ()=>{
            // this.getTime("stopMove");
            this.stopMove()
        }, this);
        this.btnNode[0].on("touchend", ()=>{
            // this.getTime("stopMove");
            this.stopMove()
        }, this);
        this.btnNode[1].on("touchstart", ()=>{
            // this.getTime("rightMove");
            if(this.newPlayIndex == 1 && GameData_red_blue_man.settingState.newPlay && GameData_red_blue_man.highestLevel == 1){
                this.newPlayIndex += 1;
                this.scheduleOnce(()=>{
                    this.newGuide(0);
                }, 1);
            }
            this.clickMove(1);
        }, this);
        this.btnNode[1].on("touchcancel", ()=>{
            // this.getTime("stopMove");
            this.stopMove()
        }, this);
        this.btnNode[1].on("touchend", ()=>{
            // this.getTime("stopMove");
            this.stopMove()
        }, this);
        this.btnNode[2].on("touchstart", ()=>{
            // this.getTime("jump");
            if(this.newPlayIndex == 3 && GameData_red_blue_man.settingState.newPlay && GameData_red_blue_man.highestLevel == 1){
                this.newPlayIndex += 1;
                this.scheduleOnce(()=>{
                    this.newGuide(3);
                }, 1);
            }
            this.pitch_on_script.jump()
        }, this);
        this.btnNode[3].on("touchstart", ()=>{
            this.cameraEvent(true);
            if(this.newPlayIndex == 4 && GameData_red_blue_man.settingState.newPlay && GameData_red_blue_man.highestLevel == 1){
                this.newPlayIndex += 1;
                this.scheduleOnce(()=>{
                    this.newGuide(4, true);
                }, 1);
            }
        }, this);
        this.btnNode[3].on("touchcancel", ()=>{this.cameraEvent(false)}, this);
        this.btnNode[3].on("touchend", ()=>{this.cameraEvent(false)}, this);
    }

    offClickEvent(){
        this.btnNode[0].off("touchstart");
        this.btnNode[0].off("touchcancel");
        this.btnNode[0].off("touchend");
        this.btnNode[1].off("touchstart");
        this.btnNode[1].off("touchcancel");
        this.btnNode[1].off("touchend");
        this.btnNode[2].off("touchstart");
        this.btnNode[3].off("touchstart");
        this.btnNode[3].off("touchcancel");
        this.btnNode[3].off("touchend");
    }

    onKeyDown(event){
        switch (event.keyCode) {
            case cc.macro.KEY.a:
                this.pitch_on_script.move(-1);
                break;
            case cc.macro.KEY.d:
                this.pitch_on_script.move(1);
                break;
            case cc.macro.KEY.space:
                // this.getTime("jump");
                this.pitch_on_script.jump();
                break;
            case cc.macro.KEY.w:
                // this.getTime("jump");
                this.pitch_on_script.jump();
                break;
        }
    }

    onKeyUp(event){
        switch (event.keyCode) {
            case cc.macro.KEY.a:
                this.pitch_on_script.stopMove();
                break;
            case cc.macro.KEY.d:
                this.pitch_on_script.stopMove();
                break;
        }
    }

    isOnce = false;
    getKey(node, type) {
        if(this.isOnce){
            return;
        }
        this.isOnce = true;
        node.stopAllActions();
        //获取钥匙在相机下所处的位置
        // 将一个世界坐标系下的点转换到屏幕坐标系下
        let newPos = cc.v2();
        cc.find("Canvas").children[0].getComponent(cc.Camera).getWorldToScreenPoint (node.position, newPos);
        node.group = "ui_red";
        node.removeFromParent();
        node.parent = this.node;
        node.setPosition(newPos);
        cc.tween(node)
            .to(0.1, {scale: 1.3})
            .to(0.3, {position: this.keyNode[type].position, scale: 1})
            .to(0, {angle: 30})
            .call(()=>{
                this.isOnce = false;
            })
            .start();

    }

    initAnim(){
        this.levelNode.active = true;
        this.levelNode.runAction(
            cc.sequence(
                cc.delayTime(0.8),
                cc.moveBy(0.4, cc.v2(0, 200)),
                cc.callFunc(()=>{
                    this.levelNode.active = false;
                })
            )
        )
    }

    protected onDestroy(): void {
        this.clearAllInterval();
    }

    // update (dt) {}
}
